package com.nbst.service.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.nbst.comnutil.LogOut;
import com.nbst.comnutil.NormalResult;
import com.nbst.comnutil.StringUtil;
import com.nbst.comnutil.UpdateShiroPermi;
import com.nbst.dao.mapper.mes.RoleMapper;
import com.nbst.dao.mapper.mes.UserRoleMapper;
import com.nbst.model.base.Base;
import com.nbst.model.base.Role;
import com.nbst.model.base.UserRole;
import com.nbst.service.base.IRolesService;

/**
 * @ClassName: RolesServiceImpl
 * @Description:角色管理Service实现层
 * @author 兵
 * @date 2017-8-17
 * 
 */
@Service
public class RolesServiceImpl implements IRolesService {
	@Autowired
	UserRoleMapper userRoleMapper;
	
	@Autowired
	RoleMapper rolesMapper;

	@Autowired
	LogOut logout;

	@Override
	public NormalResult deleteByPrimaryKey(String rId) {

		NormalResult result = new NormalResult();
		int num = 0;
		try {
			num = rolesMapper.deleteByPrimaryKey(rId);
			if (num == 1) {
				result.setCode("0000");
				result.setMessage("删除成功");
				// 清空权限缓存
				UpdateShiroPermi.cleanShiro();
			}
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("删除失败");
			result.setDataset(e);
		}
		return result;
	}

	@Override
	public NormalResult insertSelective(Role record) {

		NormalResult result = new NormalResult();
		if (StringUtil.isEmpty(record.getrId()))
			;
		record.setfDate(new Date());
		Map<String,Object> map = new HashMap<>(4);
		map.put("rName", record.getrName());
		map.put("flag", 1);// 做一个标记，作用是用来精确查询的
		map.put("sfyx", "1");
		List<Role> list = rolesMapper.findByCondition(map);
		if (list.size() > 0) {
			result.setCode("9999");
			result.setMessage("名称重复");
			return result;
		}
		int num = 0;
		try {
			num = rolesMapper.insertSelective(record);
			if (num == 1) {
				result.setCode("0000");
				result.setMessage("新增成功");
				// 清空权限缓存
				UpdateShiroPermi.cleanShiro();
				if((record.getrId())!=null)
				result.setId((record.getrId()).toString());
			}
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("新增失败");
			result.setDataset(e);
		}
		return result;
	}

	@Override
	public List<Role> findByCondition(Map<String,Object> map) {
		List<Role> list = new ArrayList<Role>();
		try {
			list = rolesMapper.findByCondition(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	public NormalResult updateByPrimaryKeySelective(Role record) {
		NormalResult result = new NormalResult();
		if (!StringUtil.isEmpty(record.getfClosed())) {
			if(record.getfClosed().intValue()==0){
				Map<String,Object> map = new HashMap<>();
				map.put("rId", record.getrId());
				List<UserRole> list = userRoleMapper.findByCondition(map);
				if (list.size()!=0) {
					result.setCode("9999");
					result.setMessage("有用户为该角色故该角色不能删除");
					return result;
				}
				record.setUpdateTime(new Date());
			}
		} else{
			record.setUpdateTime(new Date());
		}
		int num = 0;
		try {
			num = rolesMapper.updateByPrimaryKeySelective(record);
			if (num == 1) {
				result.setCode("0000");
				result.setMessage("操作成功");
				// 清空权限缓存
				UpdateShiroPermi.cleanShiro();
			} else {
				result.setCode("9999");
				result.setMessage("没有做任何改变");
			}
		} catch (Exception e) {
			logout.error(e);
			result.setCode("9999");
			result.setMessage("出错了,刷新后再试试吧");
			result.setDataset(e);
		}
		return result;
	}

	@Override
	public int count(Map<String,Object> map) {
		int total = 0;
		try {
			total = rolesMapper.count(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return total;
	}

	@Override
	public List<Role> getUserRolesList(Map<String,Object> map) {
		List<Role> list = new ArrayList<Role>();
		try {
			list = rolesMapper.getUserRolesList(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	public List<Base> getRole2User(Map<String,Object> map) {
		List<Base> list = new ArrayList<Base>();
		try {
			list = rolesMapper.getRole2User(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}

	@Override
	@Transactional
	public NormalResult addNews(Integer rId, String ids) {
		NormalResult result = new NormalResult();
		String[] id = new String[] {};
		try {

			userRoleMapper.deleteByRid(rId);
			if (!StringUtils.isEmpty(id)) {
				id = ids.split(",");
				UserRole record = new UserRole();
				record.setfDate(new Date());
				record.setrId(rId);
				int i = 0;
				for (i = 0; i < id.length; i++) {
					record.setuId(Integer.parseInt(id[i]));
					logout.info(record.toString());
					int num = userRoleMapper.insertSelective(record);
					if (num == 1) {
						result.setCode("0000");
						result.setMessage("添加成功");
					}
				}
				if (i != id.length) {
					result.setCode("9999");
					result.setMessage("批量操作失败");
				}
			} else {
				result.setCode("9999");
				result.setMessage("没有勾选任何一个用户");
			}
			// 清空权限缓存
			UpdateShiroPermi.cleanShiro();
		} catch (Exception e) {
			logout.error(e);
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();// 手动回滚
		}
		return result;

	}

	@Override
	public List<Role> findByUid(Map<String,Object> map) {
		List<Role> list = new ArrayList<Role>();
		try {
			list = rolesMapper.findByUser(map);
		} catch (Exception e) {
			logout.error(e);
		}
		return list;
	}
}